<template>
	<div class="attachment-management">
		<!-- 文件上传区域 -->
		<div class="upload-section">
			<el-upload :auto-upload="false" :show-file-list="true" :on-change="handleFileAdd"
				:before-upload="validateFile" :file-list="fileList" action="">
				<!-- 使用 trigger 插槽指定触发文件选择的按钮 -->
				<template #trigger>
					<el-button type="primary" style="margin-right: 1.25rem;">选择文件</el-button>
				</template>

				<!-- 开始上传按钮，点击时触发 startUpload 方法 -->
				<el-button type="success" @click="startUpload" :loading="isUploading" :disabled="files.length === 0">
					开始上传
				</el-button>

				<template #tip>
					<div class="el-upload__tip">
						支持上传 JPG/PNG/PDF 文件，单个文件不超过10MB
					</div>
				</template>
			</el-upload>

			<!-- 地点和航次选择 -->
			<el-form :inline="true" class="upload-params">
				<el-form-item label="地点">
					<el-input v-model="location" placeholder="请输入地点"></el-input>
				</el-form-item>
				<el-form-item label="航次">
					<el-input v-model="voyage" placeholder="请输入航次" type="number"></el-input>
				</el-form-item>
			</el-form>
		</div>

		<!-- 附件列表区域 -->
		<div class="attachment-list">
			<!-- 在表格上方添加批量操作工具栏 -->
			<div class="batch-actions" v-if="attachmentList.length > 0">
				<el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
					批量删除 ({{ selectedIds.length }})
				</el-button>
			</div>
			<el-table :data="attachmentList" v-loading="loading" style="width: 100%" border
				@selection-change="handleSelectionChange" resizable>
				<!-- 表头映射为中文 -->
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column prop="fileName" label="文件名称" width="200" />
				<el-table-column prop="location" label="地点" width="120" />
				<el-table-column prop="voyage" label="航次" width="120" />

				<!-- 预览列 -->
				<el-table-column label="预览" width="180">
					<template #default="{ row }">
						<el-image v-if="isImage(getFileType(row.fileLink))" :src="row.fileLink"
							:preview-src-list="[row.fileLink]" fit="cover" class="preview-thumb" hide-on-click-modal>
							<template #error>
								<div class="image-error">
									<i class="el-icon-picture-outline"></i>
								</div>
							</template>
						</el-image>
						<div v-else-if="isPDF(getFileType(row.fileLink))" class="pdf-preview">
							<div @click.stop="handlePreview(row)" style="display: flex; align-items: center;">
								<i class="el-icon-document"></i>
								<span style="margin-left: 8px;">{{ getFileName(row.fileLink) }}</span>
							</div>
						</div>
						<span v-else>{{ getFileType(row.fileLink) }}</span>
					</template>
				</el-table-column>

				<el-table-column prop="uploadTime" label="上传时间" width="180" />

				<!-- 操作列 -->
				<el-table-column label="操作" width="150">
					<template #default="{ row }">
						<el-button type="primary" size="mini" @click="handleDownload(row)">下载</el-button>
						<el-button type="danger" size="mini" @click="handleDelete(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<el-pagination background layout="prev, pager, next, sizes, total" :current-page="pagination.page"
				:page-size="pagination.pageSize" :page-sizes="[10, 20, 50]" :total="pagination.total"
				@current-change="handlePageChange" @size-change="handleSizeChange" />
		</div>
		<div id="pdf-container"></div>
		<!-- PDF预览对话框 -->
		<el-dialog :visible.sync="pdfDialogVisible" title="PDF预览" width="80%" @opened="renderPdf" @closed="clearPdf">
			<!-- <div class="pdf-container">
				<canvas id="pdf-canvas"></canvas>
				<div class="pdf-controls" v-if="totalPages > 0">
					<el-button @click="prevPage" :disabled="currentPage <= 1">上一页</el-button>
					<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
					<el-button @click="nextPage" :disabled="currentPage >= totalPages">下一页</el-button>
				</div>
			</div> -->
		</el-dialog>

	</div>
</template>

<script>
	import api from '@/api/api';
	import PDFObject from 'pdfobject';
	// import * as pdfjsLib from 'pdfjs-dist'
	// import 'pdfjs-dist/web/pdf_viewer.css' // 可选，用于文本层渲染

	// 设置worker路径（必须）
	// 方案A：直接引用node_modules中的文件
	// pdfjsLib.GlobalWorkerOptions.workerSrc =
	// 	require('pdfjs-dist/build/pdf.worker.min.js')
	
	export default {
		data() {
			return {
				// 上传相关
				files: [],
				fileList: [],
				location: '广东',
				voyage: 202503,
				isUploading: false,

				// 列表相关
				loading: false,
				attachmentList: [],
				pagination: {
					page: 1,
					pageSize: 10,
					total: 0
				},
				// pdf预览相关start
				pdfDialogVisible: false, //pdf可见性
				currentPdfUrl: '', //pdf链接
				currentPage: 1,
				totalPages: 0,
				pdfDoc: null,
				renderTask: null,
				// pdf预览相关end
				selectedIds: [], // 存储选中的附件ID
			}
		},
		mounted() {
			this.embedPdf();
		},
		created() {
			this.loadAttachments();
		},
		methods: {
			embedPdf() {
				PDFObject.embed(
					"http://ccc212.cn:9000/orfm/attachment/3c2918cf59f04399b42577b3ae282a89.pdf?response-content-type=application%2Fpdf&response-content-disposition=inline&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ccc212%2F20250414%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250414T132514Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=877c444f5838e5b97725fbefb04a3d768e55cb15810a1f58b2465eaa9f02e3fe",
					"#pdf-container");
			},
			// 删除相关方法
			handleSelectionChange(selection) {
				this.selectedIds = selection.map(item => item.id);
			},

			async handleDelete(id) {
				try {
					await this.$confirm('确认删除选中的附件吗？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					});

					await this.doDelete([id]);
				} catch (error) {
					if (error !== 'cancel') {
						this.$message.error('删除操作取消');
					}
				}
			},

			async handleBatchDelete() {
				try {
					await this.$confirm(`确认删除选中的 ${this.selectedIds.length} 个附件吗？`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					});

					await this.doDelete(this.selectedIds);
				} catch (error) {
					if (error !== 'cancel') {
						this.$message.error('删除操作取消');
					}
				}
			},

			async doDelete(ids) {
				try {
					const res = await api.deleteAttachment(ids);

					if (res.data.code === 0) {
						this.$message.success(res.data.msg || '删除成功');
						this.loadAttachments();
						this.selectedIds = [];
					} else {
						this.$message.error(res.data.msg || '删除失败');
					}
				} catch (error) {
					console.error('删除操作异常:', error);
					this.$message.error('删除失败，请稍后重试');
				}
			},

			// 文件上传相关方法
			handleFileAdd(file, fileList) {
				this.files.push(file.raw);
				this.fileList = fileList;
			},

			validateFile(file) {
				const isValidType = ['image/jpeg', 'image/png', 'application/pdf']
					.includes(file.type);
				const isUnder10M = file.size / 1024 / 1024 < 10;

				if (!isValidType) {
					this.$message.error('仅支持 JPG/PNG/PDF 格式');
					return false;
				}
				if (!isUnder10M) {
					this.$message.error('文件大小不能超过10MB');
					return false;
				}
				return true;
			},

			async startUpload() {
				if (!this.files.length) {
					return this.$message.warning('请先选择文件');
				}

				if (!this.location || !this.voyage) {
					return this.$message.warning('请填写地点和航次');
				}

				this.isUploading = true;

				try {
					const uploadTasks = this.files.map(file =>
						api.uploadAttachment(this.location, this.voyage, file)
					);

					const results = await Promise.all(uploadTasks);

					const success = results.every(res => res.data.code === 0);
					if (success) {
						this.$message.success('全部文件上传成功');
						this.files = [];
						this.fileList = [];
						this.loadAttachments();
					} else {
						console.log('上传的结果：', results);
						this.$message.error('部分文件上传失败');
					}
				} catch (error) {
					console.error('上传异常:', error);
					this.$message.error('上传服务不可用');
				} finally {
					this.isUploading = false;
				}
			},

			// 获取附件列表
			async loadAttachments() {
				this.loading = true;
				try {
					const res = await api.getAttachmentPage(
						this.pagination.page,
						this.pagination.pageSize
					);
					console.log('获取附件数据：', res.data.data);

					if (res.data.code === 0) {
						this.attachmentList = res.data.data.records;
						this.pagination.total = res.data.data.total;
					}
				} finally {
					this.loading = false;
				}
			},

			// 文件类型判断
			getFileType(fileLink) {
				// 从 fileLink 中提取文件扩展名
				const match = fileLink.match(/\.([a-zA-Z0-9]+)(\?|$)/);
				return match ? match[1].toLowerCase() : '未知类型';
			},

			getFileName(fileLink) {
				// 从 fileLink 中提取文件名
				const match = fileLink.match(/([^/?]+)(\?|$)/);
				return match ? match[1] : '未知文件';
			},

			isImage(fileType) {
				return ['jpg', 'jpeg', 'png', 'gif'].includes(fileType);
			},

			isPDF(fileType) {
				return fileType === 'pdf';
			},

			handlePageChange(newPage) {
				this.pagination.page = newPage;
				this.loadAttachments();
			},

			handleSizeChange(newSize) {
				this.pagination.pageSize = newSize;
				this.loadAttachments();
			},

			// pdf预览相关start
			// handlePreview(row) {
			// 	// 确保URL是正确的
			// 	if (!row.fileLink) {
			// 		this.$message.error('无效的PDF链接');
			// 		return;
			// 	}

			// 	// 处理可能的相对路径
			// 	let pdfUrl = row.fileLink;
			// 	// if (!pdfUrl.startsWith('http') && !pdfUrl.startsWith('/')) {
			// 	// 	pdfUrl = '/' + pdfUrl;
			// 	// }

			// 	this.currentPdfUrl = pdfUrl;
			// 	this.pdfDialogVisible = true;

			// 	console.log('PDF预览:', {
			// 		url: this.currentPdfUrl,
			// 		visible: this.pdfDialogVisible
			// 	});
			// },
			// async renderPdf() {
			// 	if (!this.currentPdfUrl) return

			// 	try {
			// 		// 1. 加载PDF文档
			// 		const loadingTask = pdfjsLib.getDocument(this.currentPdfUrl)
			// 		this.pdfDoc = await loadingTask.promise
			// 		this.totalPages = this.pdfDoc.numPages

			// 		// 2. 渲染第一页
			// 		await this.renderPage(this.currentPage)
			// 	} catch (error) {
			// 		console.error('PDF加载失败:', error)
			// 		this.$message.error('PDF加载失败: ' + error.message)
			// 	}
			// },

			// async renderPage(pageNum) {
			// 	if (this.renderTask) {
			// 		await this.renderTask.cancel()
			// 	}

			// 	const page = await this.pdfDoc.getPage(pageNum)
			// 	const canvas = document.getElementById('pdf-canvas')
			// 	const viewport = page.getViewport({
			// 		scale: 1.5
			// 	})

			// 	canvas.height = viewport.height
			// 	canvas.width = viewport.width

			// 	this.renderTask = page.render({
			// 		canvasContext: canvas.getContext('2d'),
			// 		viewport: viewport
			// 	})

			// 	await this.renderTask.promise
			// },

			// async prevPage() {
			// 	if (this.currentPage > 1) {
			// 		this.currentPage--
			// 		await this.renderPage(this.currentPage)
			// 	}
			// },

			// async nextPage() {
			// 	if (this.currentPage < this.totalPages) {
			// 		this.currentPage++
			// 		await this.renderPage(this.currentPage)
			// 	}
			// },

			// clearPdf() {
			// 	this.currentPage = 1
			// 	this.totalPages = 0
			// 	this.pdfDoc = null
			// 	const canvas = document.getElementById('pdf-canvas')
			// 	if (canvas) {
			// 		const ctx = canvas.getContext('2d')
			// 		ctx.clearRect(0, 0, canvas.width, canvas.height)
			// 	}
			// },
			// pfd预览相关end

			async handleDownload(row) {
				try {
					this.$message.info('准备下载文件...');
					const response = await api.downloadAttachment(row.id);

					let filename = this.getFileName(row.fileLink);
					const contentDisposition = response.headers['content-disposition'];
					if (contentDisposition) {
						const filenameMatch = contentDisposition.match(/filename=(.+)/);
						if (filenameMatch && filenameMatch[1]) {
							filename = decodeURIComponent(filenameMatch[1]);
						}
					}

					const blob = new Blob([response.data], {
						type: response.headers['content-type']
					});

					if (window.navigator.msSaveOrOpenBlob) {
						window.navigator.msSaveOrOpenBlob(blob, filename);
					} else {
						const link = document.createElement('a');
						link.href = window.URL.createObjectURL(blob);
						link.download = filename;
						link.style.display = 'none';
						document.body.appendChild(link);
						link.click();

						setTimeout(() => {
							document.body.removeChild(link);
							window.URL.revokeObjectURL(link.href);
						}, 100);
					}

					this.$message.success('下载已开始');
				} catch (error) {
					console.error('下载失败:', error);
					this.handleDownloadError(error);
				}
			},

			handleDownloadError(error) {
				if (error.response?.data instanceof Blob) {
					const reader = new FileReader();
					reader.onload = () => {
						try {
							const errorData = JSON.parse(reader.result);
							this.$message.error(errorData.msg || '下载出错');
						} catch (e) {
							this.$message.error('下载失败：服务器返回异常');
						}
					};
					reader.readAsText(error.response.data);
				} else {
					this.$message.error(error.message || '下载失败');
				}
			},
		}
	}
</script>

<style scoped>
	/* 添加一些样式以适应PDF的显示 */
	#pdf-container {
		width: 100%;
		height: 100vh;
	}

	/* pdf预览start */
	/* 确保对话框能正常显示 */
	/* 	.el-dialog__body {
		padding: 20px;
	}

	PDF预览区域样式
	.pdf-preview {
		display: flex;
		align-items: center;
		cursor: pointer;
		padding: 5px;
		border-radius: 4px;
		transition: background-color 0.3s;
	}

	.pdf-preview:hover {
		background-color: #f5f7fa;
	}

	.pdf-preview i {
		font-size: 24px;
		color: #f56c6c;
		margin-right: 8px;
	}

	.pdf-preview span {
		max-width: 120px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	} */

	/* pdf预览end */
	.batch-actions {
		width: 100%;
		display: flex;
		justify-content: flex-end;
		margin-bottom: 20px;
	}

	.attachment-management {
		padding: 20px;
	}

	.upload-section {
		margin-bottom: 30px;
		padding: 20px;
		background: #f5f7fa;
		border-radius: 4px;
	}

	.upload-params {
		margin-top: 15px;
	}

	.preview-thumb {
		width: 120px;
		height: 80px;
		object-fit: cover;
		cursor: pointer;
		border-radius: 4px;
		transition: transform 0.3s;
	}

	.preview-thumb:hover {
		transform: scale(1.05);
	}

	.pdf-preview {
		display: flex;
		align-items: center;
		cursor: pointer;
	}

	.pdf-preview i {
		font-size: 24px;
		margin-right: 8px;
		color: #F56C6C;
	}

	.pdf-preview span {
		max-width: 120px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.el-pagination {
		margin-top: 20px;
		justify-content: flex-end;
	}
</style>